import type { Directive, App } from 'vue'
import { ref } from 'vue'

const sourceNode = ref<any>(null)

const dragsortDirective: Directive = {
  mounted(el, binding) {
    // const listDom: HTMLElement = document.querySelector('.list')!
    const listDom: HTMLElement = el
    listDom.ondragstart = (e: DragEvent) => {
      const target = e.target as HTMLElement
      if (target) {
        setTimeout(() => {
          target.classList.add('moving')
        }, 0)
        sourceNode.value = target
        e.dataTransfer!.effectAllowed = 'move'
      }
    }

    listDom.ondragover = (e) => {
      e.preventDefault()
    }

    listDom.ondragenter = (e: DragEvent) => {
      e.preventDefault()
      const target = e.target as HTMLElement
      if (target) {
        if (target == listDom || target == sourceNode.value) {
          return
        }

        const children = Array.from(listDom.children)
        children.forEach((i) => {
          i.setAttribute('transition', 'all 0.3s')
        })
        const sourceIndex = children.indexOf(sourceNode.value)
        const targetIndex = children.indexOf(target)

        if (sourceIndex < targetIndex) {
          listDom.insertBefore(sourceNode.value, target.nextElementSibling)
        } else {
          listDom.insertBefore(sourceNode.value, target)
        }
      }
    }

    listDom.ondragend = (e: DragEvent) => {
      const target = e.target as HTMLElement
      if (target) {
        target.classList.remove('moving')
        const children = Array.from(listDom.children)
        const arr: unknown[] = []
        children.forEach((i) => {
          arr.push(i.innerHTML)
        })

        if (typeof binding.value === 'function') {
          binding.value(arr) // 将 arr 作为参数传递给回调函数
        }
      }
    }
  }
}
export function setupDragsortDirective(app: App) {
  app.directive('dragsort', dragsortDirective)
}

export default dragsortDirective
